//
//  RegisterViewController.m
//  TenThousand
//
//  Created by 我的 on 16/6/22.
//  Copyright © 2016年 baixue. All rights reserved.
//

#import "RegisterViewController.h"
#import <SMS_SDK/SMSSDK.h>
#import "UIScrollView+UITouch.h"
#import "WelcomeLoginViewController.h"
#import "MZTimerLabel.h"

@interface RegisterViewController ()<MZTimerLabelDelegate>
@property (weak, nonatomic) IBOutlet UITextField *password;//密码
@property (weak, nonatomic) IBOutlet UITextField *erPassword;//再次密码
@property (weak, nonatomic) IBOutlet UITextField *invitecode;//邀请码
@property (weak, nonatomic) IBOutlet UITextField *verificationCode;//验证码
@property (weak, nonatomic) IBOutlet UILabel *mobileLable;
@property (weak, nonatomic) IBOutlet UIButton *getverificationCode;
@property (weak, nonatomic) IBOutlet UITextField *payPassword;//支付密码
@property (weak, nonatomic) IBOutlet UITextField *erPayPassword;//再次输入密码
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;//下一步
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;//是否同意
@property (nonatomic, strong) NSString *yanZhengMa;

@property (nonatomic, strong) NSTimer *timer;;

@property (nonatomic, strong) MZTimerLabel *timerMZ;
@property (weak, nonatomic) IBOutlet UILabel *timerLabel;

@end

static NSInteger countDownSeconds;

@implementation RegisterViewController

- (MZTimerLabel *)timerMZ {
    if (!_timerMZ) {
        _timerMZ = [[MZTimerLabel alloc] initWithLabel:self.timerLabel andTimerType:MZTimerLabelTypeTimer];
        [_timerMZ setCountDownTime:60];
        _timerMZ.delegate = self;
        _timerMZ.timeFormat = @"重发验证码(ss秒)";
    }
    return _timerMZ;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _mobileLable.text = self.mobile;
    self.navigationItem.title = @"注册";
    [self createLeft:[UIImage imageNamed:@"ZHSZicon_03"] leftClick:^{
        [self.navigationController popViewControllerAnimated:YES];
    } right:nil rightClick:nil];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(getValidateCodeCountDown) userInfo:nil repeats:YES];
    [_timer setFireDate:[NSDate distantFuture]];
    
    _password.secureTextEntry = YES;
    _erPassword.secureTextEntry = YES;
   
    self.agreeBtn.selected = YES;//默认为选中
    
    NSLog(@"%@",_payPassword.text);
}

/**
 *  是否选中同意按钮
 *  选中 进行下一步
 *  未选中  下一步按钮enabled设为NO
 */
- (IBAction)agreeBtn:(UIButton *)sender {
    
    if (sender.selected) {
        sender.selected = NO;
        _nextBtn.enabled = NO;
    }else{
        sender.selected = YES;
        _nextBtn.enabled = YES;
    }

    
}

/**
 *  同意注册
 *
 *  判断输入是否合格
 */
- (IBAction)sureRegistered:(id)sender {
    
        [_password resignFirstResponder];
        [_erPassword resignFirstResponder];
        [_invitecode resignFirstResponder];
        
        if ([_password.text isEqualToString:@""]) {
            [ToastView showInfoWithStatus:@"密码不能为空"];
        }/*else if ([_password.text isEqualToString:@""] || _password.text.length<8){
            [ToastView showInfoWithStatus:@"密码不能少于8位"];
        }*/else if (![_erPassword.text isEqualToString:_password.text]){
            [ToastView showInfoWithStatus:@"两次密码不一致，请确认后再次输入"];
        }else if([_payPassword.text isEqualToString:_password.text]){
            [ToastView showInfoWithStatus:@"支付密码不能与登录密码一致，请重新输入"];
        }else if(![_payPassword.text isEqualToString:_erPayPassword.text]){
            [ToastView showInfoWithStatus:@"两次支付密码不一致，请确认后再次输入"];
        } else if (![self valid]) {
            [ToastView showInfoWithStatus:@"验证码输入错误，请确认后再次输入"];
        } else{
            [self registered];
        }
    
    
    
}

//获取验证码
- (IBAction)getverificationCode:(id)sender {
       //验证码: 语音 + 短信
    /*
     参数1:
     SMSGetCodeMethodSMS  短信
     SMSGetCodeMethodVoice  语音
     参数2: 接收验证码的手机号
     参数3: 区域号,  中国:86
     */
    if(![self.timerMZ counting]){
        [self.getverificationCode setTitle:@"" forState:UIControlStateNormal];
        self.timerLabel.hidden = NO;
        [self.timerMZ start];
    }
    NSDictionary *dict = @{
                           @"Tel":self.mobile,
                           @"OrderType":@"0",
                           @"OrderFrom":@"1"
                           };
    [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"Api.GetMsm" withParaments:dict withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"%@", object);
        //{VerificationCode:245301}
        NSDictionary *dic = [object[@"Data"] firstObject];
        self.yanZhengMa = dic[@"VerificationCode"];
    } withFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
    } progress:^(float progress) {
        
    }];

}

-(void)timerLabel:(MZTimerLabel*)timerLabel finshedCountDownTimerWithTime:(NSTimeInterval)countTime{
    self.timerLabel.hidden = YES;
    [self.getverificationCode setTitle:@"获取验证码" forState:UIControlStateNormal];
}

//验证验证码是否匹配
-(BOOL)valid{
    [self.view endEditing:YES];
    if ([self.verificationCode.text isEqualToString:self.yanZhengMa]) {
        return YES;
    } else {
        return NO;
    }
}

//定时器调用方法  时长1秒
- (void)getValidateCodeCountDown
{
    

    
    if (countDownSeconds >= 0) {
        [_getverificationCode setTitle:[NSString stringWithFormat:@"剩余%ld s",(long)countDownSeconds] forState:UIControlStateNormal];
        countDownSeconds--;
    }else{
        countDownSeconds = 60;
        _getverificationCode.selected = NO;
        _getverificationCode.enabled = YES;
        [_getverificationCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_timer setFireDate:[NSDate distantFuture]];
    }
}
//销毁定时器
- (void)dealloc
{
    [_timer invalidate];
}

//注册请求
- (void)registered{
    // URL:http://114.215.198.5:22853/User/ResUser 完整接口注册
    
    /**
     *  首先验证手机验证码 失败重新获取
     *  成功 发送注册请求
     */
    [self.view endEditing:YES];
//    [SMSSDK commitVerificationCode:_verificationCode.text phoneNumber:_mobile zone:@"86" result:^(NSError *error) {
//        if (error) {
//            [ToastView showInfoWithStatus:@"手机动态验证码错误"];
//        }else{
    
    /**
     用户 Id   Id
     支付密码   Payment
     Key      key
     */

    //用户注册接口

    NSDictionary *para = @{@"Password":_password.text,
                           @"LoginName":self.mobile,
                           @"OrderFrom":@"1",
                           @"Code":@""};
    NSLog(@"%@",_payPassword);
                
    [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"User.GetUserRegister" withParaments:para withSuccessBlock:^(NSDictionary *object) {
        [ToastView showInfoWithStatus:object[@"Message"]];

        if ([object[@"Code"] isEqualToString:@"00000"]) {
            for (UIViewController *temp in self.navigationController.viewControllers) {

                if ([temp isKindOfClass:[WelcomeLoginViewController class]]) {

                    [self.navigationController popToViewController:temp animated:YES];

                }
            }

        }
    } withFailureBlock:^(NSError *error) {
        
        [ToastView showInfoWithStatus:@"注册失败"];
        NSLog(@"%@",error);
    } progress:^(float progress) {
        
    }];
    
}


- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}



@end
